package nio.geek;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class DemoServer extends Thread {

    ExecutorService executor = Executors.newFixedThreadPool(8);

    private ServerSocket listenServerSocket;

    public static void main(String[] args) throws IOException {
        DemoServer server = new DemoServer();
        server.start();
        // 实例化 = connect
        Socket client = new Socket(InetAddress.getLocalHost(), server.getPort());

        OutputStream outputStream = client.getOutputStream();
        PrintWriter writer = new PrintWriter(outputStream, true);
        writer.println("hello World");

        InputStream inputStream = client.getInputStream();
        InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
        BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
        String aaa = bufferedReader.readLine();
        System.out.println("客户端:" + aaa);
    }

    public int getPort() {
        return listenServerSocket.getLocalPort();
    }

    @Override
    public void run() {
        try {
            // 监听线程
            listenServerSocket = new ServerSocket(0);
            while (true) {
                // 起一个线程处理socket
                Socket socket = listenServerSocket.accept();
                RequestHandler requestHandler = new RequestHandler(socket);
                executor.execute(requestHandler);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (listenServerSocket != null) {
                try {
                    listenServerSocket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

class RequestHandler extends Thread {
    private Socket socket;

    RequestHandler(Socket socket) {
        this.socket = socket;
    }

    @Override
    public void run() {
        try {
            InputStream inputStream = socket.getInputStream();
            InputStreamReader reader = new InputStreamReader(inputStream);
            BufferedReader bufferedReader = new BufferedReader(reader);
            String bb = bufferedReader.readLine();
            System.out.println("服务端:" + bb);

            OutputStream outputStream = socket.getOutputStream();
            PrintWriter out = new PrintWriter(outputStream, true);
            out.println("返回-" + bb);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
